// 文件路径: Server/src/main/java/com/hunterai/util/TokenUtil.java
package com.hunterai.util;

import com.hunterai.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

/**
 * 用于处理token的工具类
 */
public class TokenUtil {

    private static JwtUtil jwtUtil;

    // 静态初始化块，获取JwtUtil实例
    static {
        try {
            // 获取Spring应用上下文
            ApplicationContext context = new AnnotationConfigApplicationContext();
            jwtUtil = context.getBean(JwtUtil.class);
        } catch (Exception e) {
            // 如果无法获取Spring上下文，使用默认实现
            System.err.println("Warning: Could not get JwtUtil from Spring context, using fallback implementation");
        }
    }

    /**
     * 从token中提取用户ID
     * 
     * @param token 用户token
     * @return 用户ID
     */
    public static Long getUserIdFromToken(String token) {
        try {
            if (jwtUtil != null) {
                // 使用JWT实现
                return jwtUtil.extractUserId(token);
            } else {
                // 回退到旧的Base64实现
                return getUserIdFromBase64Token(token);
            }
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "无效的token", e);
        }
    }
    
    /**
     * 验证token是否有效
     * 
     * @param token 用户token
     * @return 是否有效
     */
    public static boolean validateToken(String token) {
        try {
            if (jwtUtil != null) {
                // 使用JWT实现
                return jwtUtil.validateToken(token);
            } else {
                // 回退到旧的Base64实现
                return validateBase64Token(token);
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 设置JwtUtil实例（用于依赖注入）
     * 
     * @param jwtUtilInstance JwtUtil实例
     */
    public static void setJwtUtil(JwtUtil jwtUtilInstance) {
        jwtUtil = jwtUtilInstance;
    }

    // 旧的Base64实现（作为回退）
    private static Long getUserIdFromBase64Token(String token) {
        try {
            // 解码token (Base64)
            byte[] decodedBytes = java.util.Base64.getDecoder().decode(token);
            String decodedToken = new String(decodedBytes);
            
            // 提取用户ID (格式：userId:username:uuid)
            String[] parts = decodedToken.split(":");
            if (parts.length < 3) {
                throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "无效的token");
            }
            
            return Long.parseLong(parts[0]);
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "无效的token", e);
        }
    }

    private static boolean validateBase64Token(String token) {
        try {
            // 解码token (Base64)
            byte[] decodedBytes = java.util.Base64.getDecoder().decode(token);
            String decodedToken = new String(decodedBytes);
            
            // 验证格式 (userId:username:uuid)
            String[] parts = decodedToken.split(":");
            return parts.length >= 3;
        } catch (Exception e) {
            return false;
        }
    }
}